<?
require_once "inc.init.php";

// THE OBJ:
$obj = new proyectos(); // <---- Change this !!!
$obj-> setDbLink($dbLink);

// GETTING:
if ( !$obj->get($_GET[$obj->_dbIndex] ) )
{
    header("Location: index.php");
    die();
}

$messenger = new Messenger();

// SAVING:
if ($_POST['action'] == 'saveField') 
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $objField->setDbLink($dbLink);
        $objField->set($_POST, true);
        $objField->portfolioID = $obj->getID();
        $objField->active ='Y';
        $objField->userID_modified = $user->getID();
        
        if($objField->save())
        {
            $messenger->setMessageType(1);
            $messenger->addMessage("Dato agregado exitosamente");
        }
        else $messenger->addMessage("Error al agregar Dato");
    }
}

if($_POST['action']=='orderContent')
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $noErrors=false;
        $newOrder = explode('&',$_POST['newOrder']);
        if (is_array($newOrder))
        {
            for($i=0; $i<count($newOrder); $i++)
            {
                $orderedItemID = intval(str_replace('mySortable[]=', '', $newOrder[$i]));
                $sql = "UPDATE ".$objField->_dbTable." SET position='". $i ."' WHERE ".$objField->_dbIndex."=".$orderedItemID;
                $noErrors = mysql_query($sql);
                if (!$noErrors) break;
            }
            if ($noErrors)
            {
                $messenger->setMessageType(1);
                $messenger->addMessage("Lista de items ordenada exitosamente.");
            }
            else $messenger->addMessage("Error al ordenar la lista de items: ". mysql_error());
        }
    } else $messenger->addMessage($lang->translate("user_action_denied"));
}

if($_GET['action'] == 'deleteField')
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $objField->setDbLink($dbLink);
        $_GET[$objField->_dbIndex]? $objField->get((int)$_GET[$objField->_dbIndex]) : null;
        if ($objField->delete())
        {
            $messenger->setMessageType(1);
            $messenger->addMessage("Dato eliminado exitosamente");
        }
        else $messenger->addMessage("Error al eliminar Dato: ". $messenger->getErrorMessage());
    }
    else $messenger->addMessage($lang->translate("user_action_denied"));
}

include DIR_ADMIN.'/common/inc.header.php';
?>
<script language="JavaScript" type="text/javascript" src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce/tinymce.min.js"></script>
<script src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/scriptaculous/scriptaculous.js?load=effects,controls,dragdrop" type="text/javascript" language="javascript" charset="utf-8"></script>
<!-- Needs to be seperate script tags! -->
<script language="JavaScript" type="text/javascript">
    tinymce.baseURL = "<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce";
    tinyMCE.init({
        theme: 'modern',
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor"
        ],
        toolbar1: "undo redo | forecolor | bold italic | link",
        theme_advanced_styles : "Texto 1=texto;Texto 2=epb3;Texto 3=titulares",
        content_css : "<?= $GLOBALS["CONF"]["url"]["root"] ?>/admin/css/inc.content.forms.css",
        mode : "specific_textareas",
        editor_selector : "mceEditor"
    });
</script>
<script type='text/javascript' src='<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/litbox.js'></script>
<script type="text/javascript">
    function deletionConfirmDialog(id)
    {
        new LITBox('Estas a punto de eliminar un contenido. Desea continuar?',
                   {type:'confirm',
                    draggable:false,
                    overlay:true,
                    resizable:false,
                    func:eliminate,
                    funcParam:id,
                    yesLabel:'Si',
                    width:350,
                    height:89});
        return void(0);
    }

    eliminate = function(id)
    {
        location.replace("?action=deleteField&<?= $obj->_dbIndex ?>=<?= $obj->getID() ?>&contentID="+id);
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places,geometry" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?= $GLOBALS['CONF']['url']['root'] ?>/css/file_explorer.css">
</head>
<body>
    <div class="Path">
        <a href="."><?= $module->name ?></a> &gt;
        <h1><a href="details.php?<?= $obj->_dbIndex ?>=<?= $obj->getID() ?>"><?= $obj->name ?></a></h1>
    </div>
    <div class="tableHeader">
        <strong>Detalles de la Secci&oacute;n</strong>
    </div>
    <table cellspacing="0" class="AbmTable">
        <tr>
            <td width="120" height="13"> Name:</td>
            <td><?= $obj->name ?></td>
        </tr>
        <tr>
            <td valign="top">Information:</td>
            <td valign="top" class="content"><?= $obj->information ?></td>
        </tr>
        <tr>
            <td valign="top">Contenido:</td>
            <td valign="top" class="content"><?= $obj->general_information ?></td>
        </tr>
        <?
        if ($module->images[get_class($obj)])
        {
            ?><tr>
                <td colspan="4">
                    <br>
                    <strong>Im&aacute;genes</strong>
                </td>
            </tr><?
            
            foreach($module->images[get_class($obj)] AS $imgID => $imgConfig)
            {
                ?><tr>
                    <td valign="top">imagen <?= ++$i ?>: <br><em><? $obj->printImageSize($imgID) ?></em></td>
                    <td colspan="3" valign="top"><? $obj->printImageHTMLThumb($imgID) ?><? $obj->printImageHTML($imgID) ?></td>
                </tr><?
            }
        }
        ?>
        <tr>
            <td>Gallery:</td>
            <td colspan="3" align="left">
            <div class="tableHeader"><b>Images</b></div>
              <?
                $photoAlbum = new FileManagerPhotoAlbum();
                $photoAlbum->setDBLink($dbLink);
                $photoAlbum->get($obj->photo_albumID);
                $displayer = new FileManagerDisplayer($photoAlbum);
                $displayer->printHTML("mediumIcon",array());
              ?>        
            </td>
        </tr>
        <tr>
            <td>Dirección:</td>
            <td><?=$obj->address?><br>
            <div id="canvas-map" style="margin-top:5px;width:500px;height:250px;display:hidden;">&nbsp;</div></td>
        </tr>
        <tr>
            <td colspan="2">
                <br>
                <strong>Datos Administrativos</strong>
            </td>
        </tr>
        <tr>
            <td>Activo:</td>
            <td><span class="ico_<?= $obj->active ?>"></span></td>
        </tr>
        <tr>
            <td colspan="2" align="right">
                <span class="button">
                    <input type="button" value="Editar" name="Editar" onClick="location.href='abm.php?<?= $obj->_dbIndex ?>=<?= $obj->getID() ?>'">
                </span>
            </td>
        </tr>
    </table>
    <div class="tableHeader">
        <strong>Agregar Dato Adicional</strong>
    </div>
    <form action="" method="post" enctype="multipart/form-data">
        <table cellspacing="0" class="AbmTable">
            <tr>
                <td width="120" height="13"> Field:</td>
                <td><input type="text" name="field_name" value=""></td>
            </tr>
            <tr>
                <td width="120" height="13"> Value:</td>
                <td><textarea name="field_value" class="mceEditor"></textarea></td>
            </tr>
            <tr>
                <td colspan="2" align="right">
                    <a class="button" href="details.php?<?= $obj->_dbIndex ?>=<?= $obj->getID() ?>"><span>Cancelar</span></a>
                    <span class="button">
                        <input type="submit" style="font-weight:bold;" value="Guardar" name="Guardar">
                    </span>
                </td>
            </tr>
        </table>
        <input type="hidden" name="action" value="saveField">
    </form>
    <div class="tableHeader"><strong>Tabla Datos Adicionales</strong></div>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin: 0" class="ListingTable">
        <tr>
            <th class="Number"><?= $indexID ?></th>
            <th>Field</th>
            <th style="width:122px;">Value</th>
            <th nowrap="nowrap" class="TableTitles" style="width: 35px; padding:0px 4px;">&nbsp;</th>
            <th nowrap="nowrap" class="TableTitles" style="width: 30px; padding:0px 4px;">&nbsp;</th>
        </tr>
    </table>
    <ul id="mySortable">
    <?
    $sql = "SELECT * FROM `fort_capital_portfolio_table_fields` WHERE portfolioID=".$obj->getID()." ORDER BY  position";
    $res = mysql_query($sql, $dbLink); 
    if(mysql_num_rows($res))
    {
        while($row = mysql_fetch_array($res))
    {
        ?><li id="content_<?= $row['contentID'] ?>">
            <table width="100%" cellpadding="0" cellspacing="0" class="ListingTable">
                <tr class="rowClickable">
                    <td class="Number" onClick="" style="width:68px;"><?= $row['contentID'] ?></td>
                    <td><?= $row['field_name'] ?></td>
                    <td class="Active" style="width:122px;"><?= $row['field_value'] ?></td>
                    <td class="LastColumn" align="center" style="cursor: default;width: 35px; padding:0px 4px;"><a title="Eliminar" href="javascript:deletionConfirmDialog(<?=$row['contentID']?>)"><img src="<?= $GLOBALS["CONF"]["url"]["admin"] ?>/images/content/ico_trashcan.gif" alt="Borrar" width="16" height="16" border="0"></a></td>
                    <td class="LastColumn Grip" align="center" style="cursor: default;width: 30px; padding:0px 4px;"></td>
                </tr>
            </table>
        </li><?
    }
    ?>
    </ul>
    <form action="" method="post" name="orderForm" id="orderForm" class="AbmTable" style="text-align:right; margin: 10px 0px; display:none">
        <span style="position: relative; top: -6px; margin-right: 10px">El orden de los contenidos ha cambiado!</span>
        <span class="button"><input type="submit" value="Guardar" name="Guardar"></span>
        <span class="button"><input type="submit" value="Cancelar" name="Cancelar" onClick="href.location='details.php?<?= $obj->_dbIndex ?>=<?= $obj->getID() ?>'"></span>
        <input name="newOrder" type="hidden" id="newOrder">
        <input name="action" type="hidden" value="orderContent">
    </form>
    <!-- Sortable table -->
    <script type="text/javascript">
        Sortable.create("mySortable", {
            handle:'grip',
            //ghosting:true,
            constraint:false,
            onUpdate:function(sortable) {
                var newOrder = Sortable.serialize(sortable);
                if (originalOrder!=newOrder) setTimeout('appearOrderForm()', 200);
                else setTimeout('fadeOrderForm()', 200);
                $('newOrder').value=newOrder;
            }
            // , onChange:function(element){$('debug').innerHTML = Sortable.serialize(element.parentNode) }
        });
        var originalOrder = Sortable.serialize("mySortable");
        function appearOrderForm()
        {
            Effect.Appear($('orderForm'));
        }
        function fadeOrderForm()
        {
            Effect.Fade($('orderForm'));
        }
    </script>
        <?
    }
    else
    {
        ?><div style="text-align:center;padding:5px;">No hay datos adicionales cargados </div><?
    }
    ?>
    <!--<div class="tableHeader"><strong>Info de sistema </strong></div>
    <table cellspacing="0" class="AbmTable">
        <tr>
            <td width="15%"><?= $module->unit ?> id: </td>
            <td colspan="3"><?= $obj->getID() ?></td>
        </tr>
        <tr>
            <td>Fecha de creaci&oacute;n :</td>
            <td><?= $obj->date_created ?></td>
            <td width="15%">Fecha &uacute;ltimo cambio:</td>
            <td><?= $obj->date_modified ?></td>
        </tr>
        <tr>
            <td>Usuario que cre&oacute;:</td>
            <td><?= $obj->userCreated ?></td>
            <td>Usuario que modific&oacute;:</td>
            <td><?= $obj->userModified ?></td>
        </tr>
    </table>-->
<script>
var options = {};
var origin = document.getElementById('inputDireccion');
// add the map to the map placeholder
<?
    if($obj->lat != '' && $obj->lng != '' && $obj->address!='')
    {
        ?>
            var LatinAmerica = new google.maps.LatLng(<?=$obj->lat?>,<?=$obj->lng?>);
            var zoomFirst = 13;
        <?
    }
    else
    {
        ?>
            var LatinAmerica = new google.maps.LatLng(-20.08525080,-59.47209040);
            var zoomFirst = 1;
        <?
    }
?>


var mapOptions = {
  zoom:zoomFirst,
  center: LatinAmerica,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('canvas-map'), mapOptions);

<?
if($obj->lat != '' && $obj->lng != '' && $obj->address != '')
{
    ?>
    var marker = new google.maps.Marker({
      map: map
    });

    //console.log(originAutocomplete.getBounds());
    var image = new google.maps.MarkerImage(
            'http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png', new google.maps.Size(71, 71),
            new google.maps.Point(0, 0), new google.maps.Point(17, 34),
            new google.maps.Size(35, 35));
    marker.setIcon(image);
    marker.setPosition( new google.maps.LatLng(<?=$obj->lat?>, <?=$obj->lng?>));
    <?
}
?>
</script>
</body>
</html>
